﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;

namespace SSHConfiger
{
    public partial class ConfigForm : Form
    {
        string version = "1.0";
        public ConfigForm()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            version = " v1.0.0.40711";
            version = " v1.0.1.40715";
            Text += version;
            txtServerName.Select();
        }

        private void btnWriteToConfig_Click(object sender, EventArgs e)
        {
            try
            {
                // 读取所有文件，如果文件不存在，则读取为空。
                string systemDrive = Path.GetPathRoot(Environment.SystemDirectory); // 获取系统盘符，如C:\
                string userProfile = Environment.GetEnvironmentVariable("USERPROFILE"); // 获取当前用户的文件夹路径
                string userName = Environment.UserName; // 获取当前用户名
                Console.WriteLine("System Drive: " + systemDrive);
                Console.WriteLine("User Profile: " + userProfile);
                Console.WriteLine("User Name: " + userName);
                var ssh_dir = Path.Combine(userProfile, ".ssh");
                var config = Path.Combine(userProfile, ".ssh\\config");
                var lines = File.ReadAllLines(config, Encoding.UTF8);
                var dicts = new Dictionary<string, List<string>>();
                List<string> curHost = new List<string>();

                foreach (string line in lines)
                {
                    string row = line.Trim().ToLower();
                    if (row.StartsWith("host "))
                    {
                        curHost = new List<string>();
                        string key = line.Trim().Split(' ')[1];
                        if (!dicts.ContainsKey(key))
                            dicts.Add(key, curHost);
                        else
                            dicts[key] = curHost;
                    }
                    curHost.Add(line);
                }

                /* 生成config文件信息 */
                string keyname = "key20240710.sec";
                List<string> list = new List<string>();
                list.Add($"Host {txtServerName.Text}");
                list.Add($"  HostName {txtServerIP.Text}");
                list.Add($"  User {txtUsername.Text}");
                list.Add($"  ServerAliveInterval 60");
                list.Add($"  ServerAliveCountMax 10");
                list.Add($"  IdentityFile ~/.ssh/{keyname}");

                if (dicts.Keys.Contains(txtServerName.Text))
                    dicts[txtServerName.Text] = list;
                else
                    dicts.Add(txtServerName.Text, list);


                // 写入文件
                StringBuilder sb = new StringBuilder();
                foreach (var key in dicts.Keys)
                {
                    sb.AppendLine(string.Join("\n", dicts[key]));
                    sb.AppendLine();
                }
                File.WriteAllText(config, sb.ToString());
                File.WriteAllText(Path.Combine(ssh_dir, keyname), common.key);
                MessageBox.Show("写入成功", "已经完成无编号注入。", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show("写入失败", "未能成功写入，原因：\n" + ex.Message,
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            var keyurl = "http://121.199.10.158:8107/downloads/configs/key1.sec";
            // string url = "http://example.com/file.txt";
            string userProfile = Environment.GetEnvironmentVariable("USERPROFILE");
            string filePath = Path.Combine(userProfile, @".ssh\key1.sec");
            Console.WriteLine(filePath);
            using (WebClient client = new WebClient())
            {
                client.DownloadFile(keyurl, filePath);
            }
        }
    }
}

/*
Host s01
    HostName 1.13.159.137
    User ubuntu
    ServerAliveInterval 60
    ServerAliveCountMax 10
    IdentityFile ~/.ssh/hao_key.pem
*/